package com.atguigu.order.service.impl;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import com.atguigu.order.bean.Order;
import com.atguigu.order.service.OrderService;
import com.atguigu.product.bean.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    RestTemplate restTemplate;

    //负载均衡
    @Autowired
    LoadBalancerClient loadBalancerClient;

    @Override
    public Order creatOrder(Long userId, Long id) {
        //远程调用获取product商品信息
        Product product = getProductFromRemoteWithLoadBalance(userId);
        Order order = new Order();
        order.setId(id);
        //TODO 需要远程调用去查询商品价格
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setUserId(userId);
        order.setNickName("张三");
        order.setAddress("尚硅谷");
        // 远程查询商品列表
        order.setProductList(Arrays.asList(product));

        return order;
    }

    //进阶版3 ： 远程调用商品列表计算商品的总价,基于注解完成负载均衡
    @LoadBalanced
    private Product getProductFromRemoteWithLoadBalanceAnnotation(Long productId) {
        String url = "http://service-product/" + productId;
        Product product = restTemplate.getForObject(url, Product.class);

        return product;
    }

    //进阶版2 ： 远程调用商品列表计算商品的总价,完成负载均衡
    private Product getProductFromRemoteWithLoadBalance(Long productId) {
        //获取商品服务所有的端口号和ip
        ServiceInstance choose = loadBalancerClient.choose("service-product");
        //先拿到一个进行访问
        //调api拿到ip和端口
        String url = "http://" + choose.getHost() + ":" + choose.getPort() + "/product/" + productId;
        log.info("远程调用商品信息的URL: {}", url);
        //给远程发送请求
        Product product = restTemplate.getForObject(url, Product.class);

        return product;
    }

    //远程调用商品列表计算商品的总价
    private Product getProductFromRemote(Long productId) {
        //获取商品服务所有的端口号和ip
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        //先拿到一个进行访问
        ServiceInstance instance = instances.get(0);
        //调api拿到ip和端口
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;
        log.info("远程调用商品信息的URL: {}", url);
        //给远程发送请求
        Product product = restTemplate.getForObject(url, Product.class);

        return product;
    }
}
